/*
   This file will be the entry point for FTP client.
   */


#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <pthread.h>
#include "globals.h"
#include "shared.h"

int logInToServer(void);
int connectToCmd(char*, char*);
bool enterPassiveMode(void);
void startThreads();
void *dataSocketCom(void*);
void *handleInput(void*);
void *cmdSocketCom(void*);

/*
   The main fucntion that will start the client
   */
int main(int argc, char **argv)
{

	//if host name and port are provided
	if(argc >= 3)
	{
		connectToCmd(argv[1], argv[2]);

	}
	//if just the host name is provided, use port 21
	else if(argc == 2)
	{
		connectToCmd(argv[1], "21");   
	}
	else
	{
		printf("Usage: cli hostname (port)\n");
		return 0;
	}



	if(enterPassiveMode())
		printf("Entered Passive Mode!\n");
	else
		printf("Failed to enter Passive mode\n");


	startThreads();


	return 0;
}

/*
 *This function will start the 3 threads that will handle the user input, command socket and data socket
 */
void startThreads()
{

	//initialize mutexes
	pthread_mutex_init(&mT0AndT1, NULL);
	pthread_mutex_init(&mShouldExit, NULL);
	pthread_mutex_init(&mListBuf, NULL);
	pthread_mutex_init(&dummyMutex, NULL);
	pthread_mutex_init(&mFileSize, NULL);

	//initialize thread conditions
	pthread_cond_init(&t0AndT1BufRdy, NULL);
	pthread_cond_init(&listBufRdy, NULL);
	pthread_cond_init(&enterPasvMode, NULL);

	
	//create threads
	if(pthread_create(&threads[0], NULL, handleInput, NULL) ||
			pthread_create(&threads[1], NULL, cmdSocketCom, NULL) ||
			pthread_create(&threads[2], NULL, dataSocketCom, NULL)){
		perror("Error creating threads");
		exit(1);
	}
	pthread_exit(NULL);

}

